package com.weiqiao.mall.rest;


import com.google.gson.Gson;
import com.mingsoft.util.StringUtil;
import com.mongodb.client.model.Filters;
import com.weiqiao.aop.log.Log;
import com.weiqiao.mall.domain.Comment;
import com.weiqiao.mall.domain.CommodityEntity;
import com.weiqiao.mall.domain.ShopComment;
import com.weiqiao.mall.service.ICommentService;
import com.weiqiao.mall.service.ICommodityService;
import com.weiqiao.utils.MallUtil;
import com.weiqiao.utils.PageUtil;
import org.bson.Document;
import org.bson.conversions.Bson;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Pageable;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.regex.Pattern;

/**
 * 交易管理控制层
 * @author PEI
 */
@RestController
@RequestMapping("/api")
public class TradeController {

    /**
     * 商品评论业务层
     */
    @Autowired
    private ICommentService commentService;

    /**
     * 商品管理业务层
     */
    @Autowired
    private ICommodityService commodityService;

    @Log("评论列表")
    @GetMapping(value = "/comment-list")
    public ResponseEntity comment(HttpServletRequest request, Pageable pageable){
        // 公司id
        int companyid = Integer.parseInt(request.getParameter("company_id"));
        // 组装查询条件
        Document doc = this.getParameterDocument(request);
        int total = commentService.getCount(companyid, doc);
        List<ShopComment> list = commentService.getCommentList(companyid, doc, pageable);
        return new ResponseEntity(PageUtil.toPage(list,total),HttpStatus.OK);
    }

    // 获取评论列表相关查询条件
    public Document getParameterDocument(HttpServletRequest request) {
        int companyId = MallUtil.getCompanyId(request);
        // 宝贝标题
        String name = request.getParameter("name");
        String level = request.getParameter("level");
        Document doc = new Document();
        // 宝贝标题名，先根据宝贝名模糊查询50条宝贝id，根据宝贝id在查询评论信息
        if (!StringUtil.isBlank(name)) {
            Pattern pattern = Pattern.compile("^.*" + name + ".*$", Pattern.CASE_INSENSITIVE);
            List<String> idList = commodityService.getCommodityIdAndLimit(companyId, new Document("name",pattern),50);
            doc.append("commodity_id",new Document("$in",idList));
        }
        // 评价类型
        if (!StringUtil.isBlank(level) && StringUtil.isInteger(level)) {
            if("1".equals(level)){
                doc.append("level",new Document("$ne",Integer.parseInt(level)));
            }else if ("100".equals(level)){
                doc.append("level",Integer.parseInt(level));
            }
        }
        return doc;
    }

    @Log("修改评论状态")
    @PostMapping(value = "/comment-state")
    public ResponseEntity updateState(HttpServletRequest request) {
        // 商品id
        String commodity_id = request.getParameter("commodity_id");
        // 评论id
        String comment_id = request.getParameter("comment_id");
        // 公司id
        int company_id = Integer.parseInt(request.getParameter("company_id"));
        // 状态 0 ：未删除 , 1：已删除
        int state = Integer.parseInt(request.getParameter("state"));
        // 修改评论信息状态
        Bson commentFilter = Filters.eq("comment_id", comment_id);
        Document doc = new Document("state", state);
        commentService.updateCommentOne(commentFilter, doc, false, company_id);
        // 根据商品id获取商品信息，修改商品的评论信息
        CommodityEntity commodity = commodityService.findCommodityById(commodity_id, company_id);
        if (commodity != null && !StringUtil.isBlank(commodity.getCommodity_id())) {
            // 获取未删除的评论，并做排序
            Bson filter_comment = Filters.and(commentFilter, Filters.eq("state", 0));
            Bson sort = Filters.eq("create_date", -1);
            List<Comment> commentList = commentService.findCommentManySortLimit(filter_comment, sort, 1, company_id);
            commodity.setComments(commentList);
            int num = commodity.getComment_times();
            if (state == 1) {
                num = num != 0 ? num - 1 : 0;
                commodity.setComment_times(num);
            } else {
                commodity.setComment_times(num + 1);
            }
            // 修改商品评论
            Bson commodityFilter = Filters.eq("commodity_id",commodity_id);
            Bson companyiFilter = Filters.eq("company_id", company_id);
            Bson filter = Filters.and(commodityFilter, companyiFilter);
            commodityService.updateCommodityByJson(company_id, filter, new Gson().toJson(commodity));
        }
        return new ResponseEntity(true,HttpStatus.OK);
    }

    @Log("获取公司所有的商品")
    @PostMapping(value = "/get-commodity-list")
    public ResponseEntity getCommodityList(HttpServletRequest request) {
        int company_id = Integer.parseInt(request.getParameter("company_id"));
        Bson filter = Filters.eq("company_id", company_id);
        //查询已上架的商品
        filter = Filters.and(filter, Filters.eq("state", 0));
        List<CommodityEntity> list = commodityService.findCommoditys(company_id, filter);
        return new ResponseEntity(list,HttpStatus.OK);
    }

    @Log("保存评论信息")
    @PostMapping(value = "/add-comment")
    public void addComment(HttpServletRequest request) {
        int company_id = Integer.parseInt(request.getParameter("company_id"));
        String commodity_id = request.getParameter("commodity_id");
        String nick = request.getParameter("nick");
        String icon_url = request.getParameter("icon_url");
        String param = request.getParameter("level");
        int level = Integer.valueOf(param);
        String content = request.getParameter("content");
        String urls = request.getParameter("urls");
        List<String> picList = StringUtil.isBlank(urls) ? new ArrayList<>() : Arrays.asList(urls.split(","));
        // 添加评论信息
        Comment entity = new Comment();
        String comment_id = String.valueOf(System.currentTimeMillis());
        entity.setComment_id(comment_id);
        entity.setCreate_date(comment_id);
        entity.setCommodity_id(commodity_id);
        entity.setContent(content);
        if (StringUtil.isBlank(icon_url)) {
            icon_url = "http://cdn.weiqiaoyun.com/weixin/74/866578720/2F1D081749A0D69BF2EAE0011B3F9B57.png";
        }
        entity.setIcon_url(icon_url);
        entity.setLevel(level);
        entity.setNick(nick);
        entity.setShow_specifications("");
        entity.setState(0);
        entity.setVideo_picture(picList);
        boolean result = commentService.addCommentOne(new Gson().toJson(entity), company_id);
        CommodityEntity commodity = commodityService.findCommodityById(commodity_id, company_id);
        if (result && commodity != null && !StringUtil.isBlank(commodity.getCommodity_id())) {
            List<Comment> list = new ArrayList<>();
            list.add(entity);
            commodity.setComment_times(commodity.getComment_times() + 1);
            commodity.setComments(list);
            Bson filter1 = Filters.eq("commodity_id", commodity_id);
            Bson filter2 = Filters.eq("company_id", company_id);
            Bson filter = Filters.and(filter1, filter2);
            commodityService.updateCommodityByJson(company_id, filter, new Gson().toJson(commodity));
        }
    }

}
